package org.restrpc.client;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import org.ssssssss.magicapi.core.service.MagicAPIService;
import org.restrpc.client.NativeRpcClient;
import org.restrpc.client.RpcClient;

public class RestRpc {
	private static NativeRpcClient rpcClient = null;
	private static MagicAPIService service;

	public static String MESSAGE_API = "/platform/restrpc/messageApi";
	
	public static void setService(MagicAPIService service) {
		RestRpc.service = service;
	}
	public static MagicAPIService getService() {
		return service;
	}

	public static void setApi(String messageApi) {
		RestRpc.MESSAGE_API = messageApi;
	}
	public static boolean loadLib(String libPath) {
		if(rpcClient==null) {
			rpcClient = new NativeRpcClient(libPath);
			return rpcClient!=null;
		}
		else return true;		
	}
	public static boolean connect(String ip, int port) {
		if(rpcClient==null) {
			return false;
		}
		else return rpcClient.connect(ip+":"+port);
	}
	public static void close() {
		if(rpcClient!=null) {
			rpcClient.close();
			rpcClient = null;
		}
	}
	public static NativeRpcClient getClient() {
		return rpcClient;
	}
	
	public static boolean subscribe(String key,String messageApi) {
		if(rpcClient==null) return false;
		rpcClient.subscribe(new RpcPubSubImpl(), key);
		return true;
//	    rpcClient.subscribe((channel, message) ->
//	    {  
//		        System.out.println(channel +  " receive message:" +message);
//	        	Map<String, Object> params = new HashMap<>();
//		        params.put("message",message);
//		        params.put("channel",channel);
//		        RestRpc.getService().execute("GET", messageApi, params);
//	    }, key);
//	    return true;
	}
	
	public static void testApi() {
		String method = "GET";
        Map<String, Object> params = new HashMap<>();
        params.put("message","message111");
        params.put("channel","1111channel");
        RestRpc.getService().execute(method, RestRpc.MESSAGE_API, params);		
	}
}
